// const {ipcRenderer} = require('electron')
;(() => {
  const md5 = require('md5')
  const { ipcRenderer } = require('electron')
  const AccountUtil = require('../utils/AccountUtil')
  let loginInfo = {}
  let remember = !!Number(window.localStorage.getItem('remember')) || false

  ;(function initInputValue() {
    if (remember) {
      loginInfo = JSON.parse(window.localStorage.getItem('loginInfo')) || {}
      document.getElementById('remember').checked = remember
      for (const key in loginInfo) {
        const inputElem = document.getElementById(key)
        if (inputElem) {
          inputElem.value = loginInfo[key]
        }
      }
    }
  })()
  ;(function addInputListener() {
    const inputs = document.querySelectorAll('input[type="text"]')
    for (let index = 0; index < inputs.length; index++) {
      const input = inputs[index]
      input.addEventListener('input', () => {
        loginInfo[input.id] = input.value
        showHint(input.id, true)
      })
    }
    const passwordInput = document.getElementById('password')
    passwordInput.addEventListener('input', () => {
      loginInfo.password = md5(passwordInput.value)
      showHint(passwordInput.id, true)
    })
  })()
  ;(function addCheckListener() {
    const checkBox = document.getElementById('remember')
    remember = checkBox.checked
    checkBox.addEventListener('change', () => {
      remember = checkBox.checked
    })
  })()
  // ;(function setCloseButton(){
  //   if (process.platform === 'darwin') {
  //     document.getElementById('close-button').remove()
  //   }
  // })()

  function showHint(name, isValid, hint) {
    const hintSpan = document.getElementById(`${name}-hint`)
    if (hintSpan) {
      hintSpan.innerText = hint
      hintSpan.style.visibility = isValid ? 'hidden' : 'visible'
    }
  }

  function checkInput() {
    const nodeIdReg = /\d{4}/
    const telephoneReg = /^1[3456789]\d{9}$/
    if (!nodeIdReg.test(loginInfo.nodeId))
      return showHint('nodeId', false, '请输入正确的服务器编号') || false
    else showHint('nodeId', true)
    if (!telephoneReg.test(loginInfo.telephone))
      return showHint('telephone', false, '无效的手机号') || false
    else showHint('telephone', true)
    if (!loginInfo.password) return showHint('password', false, '请输入密码')
    else showHint('password', true)
    return true
  }

  function getHostByNodeId() {
    return global.network
      .post('http://csw.ciicloud.cn/center/swcenter/getNode', {
        nodeNo: loginInfo.nodeId
      })
      .then(res => {
        console.log(res)
        if (res.status === 0) return res.nodeConfigBean.domainName
        return Promise.reject(new Error(res.message || '未知错误'))
      })
      .catch(err => {
        return `csw${loginInfo.nodeId}.ciicloud.cn`
      })
  }

  function changeLoginState(state) {
    return Promise.resolve()
  }

  function loginOnService(domain) {
    const loginUrl = `http://${domain}:34780/user/login`
    const telephone = md5(loginInfo.telephone)
    return global.network.post(loginUrl, {...loginInfo, telephone})
    .then(res => {
      console.log(res)
      if (res.resultCode === 1) {
        const userInfo = res.data
        userInfo.password = loginInfo.password
        userInfo.domain = domain
        return userInfo
      } else {
        return Promise.reject(new Error(res.resultMsg || '未知错误'))
      }
    })
  }
  function changeToMainWindow(){
    ipcRenderer.send('application-message', 'login', userInfo)
  }
  function saveLoginInfo(userInfo){
    global.userInfo = userInfo
    if (remember) {
      window.localStorage.setItem('loginInfo', JSON.stringify(loginInfo))
      AccountUtil.updateUserInfo(userInfo)
    }
    window.localStorage.setItem('remember', String(Number(remember)))
    return userInfo
  }
  ;(function addButtonListener() {
    const loginBtn = document.getElementById('login-button')
    loginBtn.addEventListener('click', () => {
      if (checkInput()) {
        changeLoginState('logining')
        getHostByNodeId()
          .then(loginOnService)
          .then(saveLoginInfo)
          .then(changeToMainWindow)
          .catch(err => {
            console.log(err)
            showHint('bottom', false, String(err.message || err))
          })
      }
    })
    const closeButton = document.getElementById('close-button')
    closeButton.addEventListener('click', () => {
      ipcRenderer.send('application-message', 'login-close')
    })
  })()
})()
